<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />
    <!-- 分配Agent车辆Package -->
    <div>
      <el-dialog
        width="35%"
        title="Allot Agent Car Package"
        :visible.sync="dialogFormVisible"
      >
        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="Agent" :label-width="formLabelWidth">
            <el-select
              placeholder="Please Select Agent"
              :clearable="true"
              v-model="agentValue"
              style="width:250px"
            >
              <el-option
                v-for="item in agentArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="Car Package" :label-width="formLabelWidth">
            <el-select
              placeholder="Please Select Car Package"
              :clearable="true"
              v-model="agentIdValue"
              multiple
              style="width:250px"
            >
              <el-option
                v-for="item in agentIdArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div>Agent Already Add Car Package：</div>
        <el-table :data="inquireAgentData">
          <el-table-column
            property="name"
            label="Package Name"
            align="center"
          />
          <el-table-column
            property="id"
            label="id"
            width="150"
            align="center"
          />
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="affirmAgentFn">Confirm</el-button>
        </div>
      </el-dialog>
    </div>
    <r-table
      :tableHandles="tableHandles"
      :isSelection="false"
      :isIndex="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      :isHandle="true"
      @refresh="init()"
    >
    </r-table>
    <r-form
      :formRules="formRules"
      :formHandle="formHandle"
      :formData="formData"
      :formCols="formCols"
      ref="elForm"
      labelWidth="200px"
      dialogWidth="700px"
      :isHandle="true"
    />
  </div>
</template>
<script>
export default {
  data() {
    return {
      agentArr: [],
      agentIdArr: [],
      dialogFormVisible: false,
      formLabelWidth: "80px",
      agentValue: "",
      agentIdValue: [],
      inquireAgentData: [],
      searchData: {
        name: "",
        typeId: ""
      },
      searchForm: [
        {
          type: "input",
          prop: "name",
          placeholder: "Package Name",
          width: 180
        },

        {
          type: "select",
          placeholder: "CarType",
          width: 180,
          prop: "typeId",
          options: []
        }
      ],
      searchHandle: [
        {
          label: "Search",
          type: "success",
          plain: true,
          icon: "el-icon-search",
          handle: e => {
            this.zeroFn();
            this.init();
          }
        },
        {
          label: "Reset",
          buttonss: true,
          icon: "el-icon-refresh-right",
          handle: e => {
            this.searchData = {
              name: "",
              typeId: ""
            };
            this.zeroFn();
            this.init();
          }
        }
      ],

      tableHandles: [
        {
          label: "Add",
          type: "primary",
          plain: true,
          isShow: true,
          handle: e => this.elFormVisible(),
          isShow: row => {
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        {
          label: "Allot Agent BatteryType",
          type: "primary",
          plain: true,
          handle: e => {
            this.dialogFormVisible = true;
            this.inquireAgentData = [];
            this.agentIdValue = [];
          },
          isShow: row => {
            return sessionStorage.role == "operator" ? true : false;
          }
        }
      ],
      tableData: [],
      tableCols: [
        {
          label: "Package Name",
          prop: "name"
        },
        {
          label: "CarType",
          prop: "typeName"
        },
        {
          label: "Package Days",
          prop: "days",
          formatter: e => (e.days ? e.days + "天" : "--")
        },
        {
          label: "Package Price",
          prop: "price",
          formatter: e => (e.price ? e.price + "元" : "--")
        },
        {
          label: "whether Forbidden",
          prop: "status",
          type: "tag",
          formatter: e =>
            e.status == 0 ? "Forbidden" : e.status == 1 ? "Enable" : "--",
          theme: e => (e.status == 0 ? "warning" : "primary")
        },
        {
          label: "Creation Time",
          prop: "ctime"
        },
        {
          label: "Operations",
          type: "button",
          width: 200,
          btnList: [
            {
              label: "Edit",
              type: "primary",
              size: "mini",
              plain: true,
              handle: row => this.elFormDetail(row)
            },
            {
              label: "Delete",
              type: "danger",
              size: "mini",
              plain: true,
              handle: row => {
                this.$confirm("Confirm Delete?", "Hint", {
                  confirmButtonText: "Confirm",
                  cancelButtonText: "Cancel",
                  type: "warning"
                })
                  .then(async () => {
                    const res = await this.apis.carMealRemove(row.id);
                    this.$message({
                      type: "success",
                      message: "Delete Success!"
                    });
                    this.init();
                  })
                  .catch(() => {});
              }
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },
      formData: {
        id: "",
        name: "",
        typeId: "",
        typeName: "",
        days: "",
        price: "",
        status: ""
      },
      btTypeIdList: [],
      formCols: [
        { type: "input", label: "Package Name", width: 350, prop: "name" },
        {
          type: "select",
          label: "CarType",
          width: 350,
          prop: "typeName",
          options: []
        },
        {
          type: "input",
          label: "Package Days",
          width: 350,
          prop: "days"
          // remark: "天"
        },
        {
          type: "input",
          label: "Package Price",
          width: 350,
          prop: "price"
          // remark: "元"
        },
        {
          type: "switch",
          label: "PackageStatus",
          width: 350,
          prop: "status",
          values: [1, 0]
          // change: (e) => {
          //   this.switChchangeFn()
          // }
        }
      ],
      formRules: {
        name: [{ required: true, message: "Please Enter", trigger: "blur" }],
        typeName: [
          { required: true, message: "Please Select", trigger: "blur" }
        ],
        days: [{ required: true, message: "Please Enter", trigger: "blur" }],
        price: [{ required: true, message: "Please Enter", trigger: "blur" }]
      },
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ]
    };
  },
  async mounted() {
    this.init();
    this.agentFn();
    this.carTypeFn();
  },
  watch: {
    dialogFormVisible: {
      handler(newValue, oldValue) {
        if (!newValue && oldValue) {
          this.agentValue = "";
          this.agentIdValue = [];
        } else if (newValue && !oldValue) {
          this.agentValue = "";
          this.agentIdValue = [];
        }
      },
      deep: true // 深度监听
    },
    agentValue: {
      handler(newValue) {
        // console.log('新', newValue, '---旧', oldValue)
        if (newValue) {
          this.yesAgentFn(newValue);
        } else {
          return;
        }
      },
      deep: true // 深度监听
    },
    "formData.typeName": {
      handler(newValue) {
        if (newValue) {
          console.log(444, newValue);
          this.btTypeIdList.forEach(i => {
            let id = newValue.split(":")[1];
            if (Number(i.id) === Number(id)) {
              this.formData.typeId = i.id;
              this.formData.typeName = i.name;
            } else {
              return;
            }
          });
        } else {
          this.isformDatas = false;
          return;
        }
      },
      deep: true // 深度监听
    }
  },
  methods: {
    zeroFn() {
      this.tablePage.limit = 10;
      this.tablePage.page = 1;
      this.tablePage.total = 0;
    },
    async init() {
      let parm = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      };
      let res = await this.apis.carMealList(parm);
      if (res) {
        this.tableData = res.rows;
        this.tablePage.total = res.total;
        this.agentIdArr = [];
        this.tableData.forEach(i => {
          let testAgentArr = {
            id: i.id,
            name: i.name
          };
          this.agentIdArr.push(testAgentArr);
        });
      }
    },
    // 拿到车辆Typeid
    async carTypeFn() {
      let parm = {
        pageNum: 1,
        pageSize: 100,
        name: ""
      };
      let res = await this.apis.carTypeList(parm);
      this.btTypeIdList = res.rows || [];
      if (res.rows.length !== 0) {
        let options = [];
        let options1 = [];
        res.rows.forEach(i => {
          options.push({
            value: i.id,
            label: i.name
          });
          options1.push({
            value: i.name + ":" + i.id,
            label: i.name
          });
        });

        this.formCols[
          this.labIndex2(this.formCols, "typeName")
        ].options = options1;
        this.searchForm[
          this.labIndex2(this.searchForm, "typeId")
        ].options = options;
      }
    },

    // 拿到Agentid列表
    async agentFn() {
      let param = {
        pageNum: 1,
        pageSize: 100
      };
      let res = await this.apis.agent_list(param);
      let arr = res.rows;
      arr.forEach(i => {
        let testAgentArr = {
          id: i.id,
          name: i.name
        };
        this.agentArr.push(testAgentArr);
      });
    },

    // 获取Agent下已经分配好的---车辆Package列表
    async yesAgentFn(id) {
      this.agentIdValue = [];
      let res = await this.apis.carMealAgentItem(id);
      this.inquireAgentData = res.data || [];
      if (res.code == 200 && res.data.length !== 0) {
        res.data.forEach(i => {
          this.agentIdValue.push(i.id);
        });
      }
      console.log(9999, this.inquireAgentData);
    },
    // Agent绑定车辆Package
    async affirmAgentFn() {
      if (!this.agentValue) {
        this.$message({
          message: "Please Select Agent",
          type: "error"
        });
        return false;
      }
      if (this.agentIdValue.length === 0) {
        this.$message({
          message: "Please Select Car Package",
          type: "error"
        });
        return false;
      }

      let params = {
        id: this.agentValue,
        allots: this.agentIdValue
      };
      let res = await this.apis.carMealAllotAgent(params);
      this.$message({
        type: res.code == 200 ? "success" : "error",
        message: res.msg
      });
      this.dialogFormVisible = false;
    },

    // Edit/Add---确定按钮
    async elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(async valid => {
        if (valid) {
          var res;
          if (this.formData.id) {
            //Edit
            res = await this.apis.carMealEdit(this.formData);
          } else {
            //Add
            res = await this.apis.carMealSave(this.formData);
          }
          setTimeout(() => {
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.msg
            });
            this.init();
            this.elFormVisible();
          }, 600);
        }
      });
    },

    // Edit按钮
    elFormDetail(row) {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key];
      });
      this.formData.id = row.id;
      this.elFormVisible();
    }
  }
};
</script>
<style scoped lang="scss"></style>
